﻿using DSVISUAL.LocalDNS.Services;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace DSVISUAL.LocalDNS.Views
{
    public partial class PortMapConfigForm : Form
    {
        DataTable dt;
        public PortMapConfigForm()
        {
            InitializeComponent();
            this.FormClosing += PortMapConfigForm_FormClosing;
            dt = PortMapService.LoadDataSource();
            this.dataGridView1.DataSource = dt;
            this.dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
            this.StartPosition = FormStartPosition.CenterParent;
            aUTOSTARTPORTMARSERVICEToolStripMenuItem.Checked = PortMapService.GetIsAutoStart();
            if (aUTOSTARTPORTMARSERVICEToolStripMenuItem.Checked) {
                PortMapService.Start(dt);
            }
        }

        private void PortMapConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var d = this.dataGridView1.DataSource as DataTable;
            PortMapService.SaveDataSource(d);
        }

        private void DataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                this.propertyGrid1.SelectedObject = this.dataGridView1.SelectedRows[0].DataBoundItem;
            }
            else
            {
                this.propertyGrid1.SelectedObject = null;
            }
        }

        private void sTARTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var num = PortMapService.Start(dt);
            MessageBox.Show(this, $"{num} thread started/ {PortMapService.Listeners.Count} threads total", "PORT MAP SERVICE");
        }

        private void sTOPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PortMapService.StopAll(dt);
        }
        private void aUTOSTARTPORTMARSERVICEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var mAuto = sender as ToolStripMenuItem;
            PortMapService.SetIsAutoStart(!mAuto.Checked);
            mAuto.Checked = !mAuto.Checked;
        }
    }
}
